package com.mes.utils;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	/**
	 * json字符串转为集合
	 * @param jsonStr
	 * @param ref
	 * @param ignoreUnkownProperty
	 * @return
	 */
	public static <T> T parseJson(String jsonStr, TypeReference<T> ref, boolean ignoreUnkownProperty) {
		ObjectMapper om = new ObjectMapper();
		if(ignoreUnkownProperty) {
			om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		}
		try {
			return om.readValue(jsonStr, ref);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * json字符串转为集合
	 * @param jsonStr
	 * @param ref
	 * @return
	 */
	public static <T> T parseJson(String jsonStr, TypeReference<T> ref) {
		return parseJson(jsonStr, ref, false);
	}
	
	/**
	 * json字符串转为POJO
	 * @param jsonStr
	 * @param obj
	 * @param ignoreUnkownProperty
	 * @return
	 */
	public static <T> T parseJson(String jsonStr, Class<T> obj, boolean ignoreUnkownProperty) {
		ObjectMapper om = new ObjectMapper();
		if(ignoreUnkownProperty) {
			om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		}
		try {
			return om.readValue(jsonStr, obj);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static <T> T parseJson(String jsonStr, Class<T> obj) {
		return parseJson(jsonStr, obj, true);
	}
	
	/**
	 * 对象转Json
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj) {
		ObjectMapper om = new ObjectMapper();
		try {
			return om.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
